﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FlowChartDemo
{
    public partial class FormDemo02V2 : FormBase
    {
        public FormDemo02V2()
        {
            InitializeComponent();
            DemoTitle = "第03节随课Demo  Part2";
            DemoNote = "效果：在【任意】两个矩形之间添加【一条】直线，连接两个形状的中心";
        }

        /// <summary>
        /// 矩形定义
        /// </summary>
        public class RectShape
        {
            /// <summary>
            /// 矩形ID
            /// </summary>
            public string Id { get; set; }
            /// <summary>
            /// 矩形位置和尺寸
            /// </summary>
            public Rectangle Rect { get; set; }
        }

        /// <summary>
        /// 直线连线定义
        /// </summary>
        public class LineLink
        {
            /// <summary>
            /// 连线ID
            /// </summary>
            public string Id { get; set; }
            /// <summary>
            /// 连线开始形状ID
            /// </summary>
            public string StartShapeId { get; set; }
            /// <summary>
            /// 连线结束形状ID
            /// </summary>
            public string EndShapeId { get; set; }
        }

        /// <summary>
        /// 当前界面矩形集合
        /// </summary>
        List<RectShape> Shapes = new List<RectShape>();
        /// <summary>
        /// 当前界面连线集合
        /// </summary>
        List<LineLink> Links = new List<LineLink>();

        /// <summary>
        /// 画一个矩形(不同颜色)
        /// </summary>
        /// <param name="g"></param>
        /// <param name="shape"></param>
        void DrawShape2(Graphics g, RectShape shape)
        {
            var index = Shapes.FindIndex(a => a.Id == shape.Id);
            g.FillRectangle(GetBrush(index), shape.Rect);
            g.DrawString(shape.Id, Font, Brushes.White, shape.Rect);
        }

        /// <summary>
        /// 绘制一条连线
        /// </summary>
        /// <param name="g"></param>
        /// <param name="line"></param>
        void DrawLine(Graphics g,LineLink line)
        {
            //通过连线的开始形状ID和结束形状ID，计算两个形状的中心点坐标
            var startPoint = GetCentertPoint(line.StartShapeId);
            var endPoint = GetCentertPoint(line.EndShapeId);
            //绘制一条直线
            g.DrawLine(Pens.Black, startPoint, endPoint);
        }

        /// <summary>
        /// 重新绘制当前所有矩形和连线
        /// </summary>
        /// <param name="g"></param>
        void DrawAll(Graphics g)
        {
            g.Clear(panel1.BackColor) ;
            //绘制所有形状
            foreach (var sp in Shapes)
            {
                DrawShape2(g, sp);
            }
            //绘制所有连线
            foreach (var ln in Links)
            {
                DrawLine(g, ln);
            }
        }

        /// <summary>
        /// 当前是否有鼠标按下，且有矩形被选中
        /// </summary>
        bool _isMouseDown = false;
        /// <summary>
        /// 最后一次鼠标的位置
        /// </summary>
        Point _lastMouseLocation = Point.Empty;
        /// <summary>
        /// 当前被鼠标选中的矩形
        /// </summary>
        RectShape _selectedShape = null;

        /// <summary>
        /// 添加连线时选中的第一个形状
        /// </summary>
        RectShape _selectedStartShape = null;
        /// <summary>
        /// 添加连线时选中的第二个形状
        /// </summary>
        RectShape _selectedEndShape = null;
        /// <summary>
        /// 是否正添加连线
        /// </summary>
        bool _isAddLink = false;

        /// <summary>
        /// 获取不同的背景颜色
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        Brush GetBrush(int i)
        {
            switch (i)
            {
                case 0: return Brushes.Red;
                case 1: return Brushes.Green;
                case 2: return Brushes.Blue;
                case 3: return Brushes.Orange;
                case 4: return Brushes.Purple;
                default: return Brushes.Red;
            }
        }

        /// <summary>
        /// 根据形状ID获取形状的中心点，以作为连线的起点或终点
        /// </summary>
        /// <param name="shapeId"></param>
        /// <returns></returns>
        Point GetCentertPoint(string shapeId)
        {
            var sp = Shapes.Find(a => a.Id == shapeId);
            if (sp != null)
            {
                var line1X = sp.Rect.X + sp.Rect.Width / 2;
                var line1Y = sp.Rect.Y + sp.Rect.Height / 2;
                return new Point(line1X, line1Y);
            }
            return Point.Empty;
        }


        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            var rs = new RectShape()
            {
                Id = "矩形" + (Shapes.Count + 1),
                Rect = new Rectangle()
                {
                    X = 50,
                    Y = 50,
                    Width = 100,
                    Height = 100,
                },
            };
            Shapes.Add(rs);

            //重绘所有矩形
            DrawAll(panel1.CreateGraphics());
        }

        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            //当鼠标按下时

            //取最上方的矩形，也就是最后添加的矩形
            var sp = Shapes.FindLast(a => a.Rect.Contains(e.Location));
            if (sp != null)
            {
                //证明取到了矩形

                //判断是否正在添加连线
                if (_isAddLink)
                {
                    //正在添加连线
                    if (_selectedStartShape == null)
                    {
                        //如果开始形状还没选择，则设置开始形状
                        _selectedStartShape = sp;
                        toolStripStatusLabel1.Text = "请点击第2个形状";
                    }
                    else if (_selectedEndShape == null)
                    {
                        //判断第2个形状是否是第1个形状
                        if (_selectedStartShape.Id == sp.Id)
                        {
                            toolStripStatusLabel1.Text = "不可选择同一个形状，请重新点击第2个形状";
                        }
                        else
                        {
                            //如果结束形状还没选择，则设置结束形状
                            _selectedEndShape = sp;

                            //两个形状都设置了，便添加一条新连线
                            Links.Add(new LineLink()
                            {
                                Id = "连线" + (Links.Count + 1),
                                StartShapeId = _selectedStartShape.Id,
                                EndShapeId = _selectedEndShape.Id,
                            });
                            //两个形状都已选择，结束添加连线状态
                            _isAddLink = false;
                            toolStripStatusLabel1.Text = "";
                            //重绘以显示连线
                            DrawAll(panel1.CreateGraphics());
                        }
                    }

                }
                else
                {
                    //如果没有在添加连线，则正常选中矩形

                    //设置状态及选中矩形
                    _isMouseDown = true;
                    _lastMouseLocation = e.Location;
                    _selectedShape = sp;
                }
            }
        }

        private void panel1_MouseMove(object sender, MouseEventArgs e)
        {
            //当鼠标移动时

            //如果处于添加连线时，则不移动形状
            if (_isAddLink) return;

            if (_isMouseDown)
            {
                //当且仅当：有鼠标按下且有矩形被选中时，才进行后续操作

                //改变选中矩形的位置信息，随着鼠标移动而移动

                //计算鼠标位置变化信息
                var moveX = e.Location.X - _lastMouseLocation.X;
                var moveY = e.Location.Y - _lastMouseLocation.Y;

                //将选中形状的位置进行同样的变化
                var oldXY = _selectedShape.Rect.Location;
                oldXY.Offset(moveX, moveY);
                _selectedShape.Rect = new Rectangle(oldXY, _selectedShape.Rect.Size);

                //记录当前鼠标位置
                _lastMouseLocation.Offset(moveX, moveY);

                //重绘所有矩形
                DrawAll(panel1.CreateGraphics());
            }

        }

        private void panel1_MouseUp(object sender, MouseEventArgs e)
        {
            //当鼠标松开时
            if (_isMouseDown)
            {
                //当且仅当：有鼠标按下且有矩形被选中时，才进行后续操作

                //重置相关记录信息
                _isMouseDown = false;
                _lastMouseLocation = Point.Empty;
                _selectedShape = null;
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            _isAddLink = true;
            _selectedStartShape = null;
            _selectedEndShape = null;
            toolStripStatusLabel1.Text = "请点击第1个形状";
        }
    }


}
